import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
const PayIndex = () => import('@/views/member/pay/index')
const routes = [
  {
    path: '/',
    component: () => import('@/views/Layout'),
    children: [{
      path: '/',
      component: () => import('@/views/home')
    }, {
      path: '/category/:id',
      component: () => import('../views/category/Index.vue')
    }, {
      path: '/category/sub/:id',
      component: () => import('../views/category/components/sub-bread.vue')
    }, {
      path: '/product/:id',
      component: () => import('@/views/goods/index')
    }]
  },
  { path: '/login', component: () => import('@/views/login/index') },
  {
    path: '/cart', component: () => import('@/views/cart/index')
  },
  {
    path: '/member/checkout', component: () => import('@/views/member/pay/checkout')
  },
  // 带参数 query
  { path: '/member/pay', component: PayIndex }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  // 每次路由切换滚动到页面顶部
  scrollBehavior () {
    // vue2.0 用 x:0 和 y::0控制
    // vue3.0用left: 0, top: 0控制
    return { left: 0, top: 0 }
  }
})

// 前置路由守卫
router.beforeEach((to, from, next) => {
  // 需要判断用户是否登陆的地方 /member
  // console.log(store)
  const { profile } = store.state.user
  // const token = store.state.user.profile
  if (!profile.token && to.path.startsWith('/member')) {
    return next('/login?redirect=' + encodeURIComponent(to.fullPath))
  }
  next()
})
export default router
